package com.dxx.D201910312055.dxx;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.Image;
import android.media.ImageReader;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

import static com.dxx.D201910312055.dxx.AutoService.mService;


//如果那个Activity需要截屏求继承这里
public class ScreenActivity extends Activity {
    private int width, height, dpi;
    private MediaProjectionManager mediaProjectionManager = null;
    private int REQUEST_CODE = 0x001;
    //getBitmap()内部返回
    private Bitmap getBitmap = null;
    //    这个才是获取关键
    public static MediaProjection mediaProjection = null;

    private static TextView floatingWindow_TextView1;
    private static FloatingWindow floatingWindow;


    private void startScreenShot() {
        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        if (windowManager != null) {
            DisplayMetrics displayMetrics = new DisplayMetrics();
            windowManager.getDefaultDisplay().getMetrics(displayMetrics);
            width = displayMetrics.widthPixels;
            height = displayMetrics.heightPixels;
            dpi = displayMetrics.densityDpi;
        }

        mediaProjectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
        if (mediaProjectionManager != null) {
            startActivityForResult(mediaProjectionManager.createScreenCaptureIntent(), REQUEST_CODE);
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }


    //    悬浮窗截屏例子
    //   申请截图权限需要当前Acitivity页面才可以，有了权限值后就可以在其他页面使用
    //重新打开这个Acitivity，会覆盖前面的，然后需要重新申请权限就行
    public void floatingWindow() {
//防止重复创建和创建的重复性

        if (floatingWindow != null && floatingWindow_TextView1 != null) {
            floatingWindow.removeView(floatingWindow_TextView1);
            floatingWindow_TextView1 = null;

        }
        if (floatingWindow == null) {
            floatingWindow = new FloatingWindow(this);

        }
        if (floatingWindow_TextView1 == null) {


            floatingWindow_TextView1 = floatingWindow.creat_View();
            floatingWindow_TextView1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bitmap bitmap = Screen();
                    if (bitmap != null) {
                        saveBitmap(bitmap);
                        Toast.makeText(mService, "保存成功", Toast.LENGTH_SHORT).show();
                    }


//                Screen();
//                System.out.println(view.getVisibility());
//                int Visibility_int = 0;
//                if (Visibility_int == view.getVisibility()) {
//                    view.setVisibility(View.GONE);
//                } else {
//                    view.setVisibility(View.VISIBLE);
//                }


                }
            });
        }

    }


    //    封装其它然后调用这个就行
    public Bitmap Screen() {

        long time_long = System.currentTimeMillis();
        //判断获取的关键是否存在，没有就申请权限
        if (mediaProjection == null) {
            startScreenShot();
            //        系统值==授权码,系统值只有授权的时候才相同，然后就可能变化其他值了
            while (true) {
                if (RESULT_OK == REQUEST_CODE) {
//                    Toast.makeText(this, "申请权限成功", Toast.LENGTH_LONG).show();
                    break;
                }
                if (System.currentTimeMillis() > time_long + 3000) {
//                    Toast.makeText(this, "权限时效过时", Toast.LENGTH_SHORT).show();
                    break;
                }

            }


        }
        if (mediaProjection != null) {
            getBitmap();
//            更新bitmap
        }

        if (getBitmap == null) {
            Toast.makeText(this, "截图数据返回异常", Toast.LENGTH_SHORT).show();
            return null;
        }
        Bitmap b = getBitmap.copy(Bitmap.Config.ARGB_8888, true);

        getBitmap = null;
        return b;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data);
        Toast.makeText(this, "申请权限成功", Toast.LENGTH_SHORT).show();
//        MediaProjection mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data);
//        if (mediaProjection != null) {
//            getBitmap(mediaProjection);
//        }
    }

    private void getBitmap() {
        ImageReader imageReader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 3);
        mediaProjection.createVirtualDisplay("screen_shot",
                width, height, dpi, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                imageReader.getSurface(), null, null);

        Image image = imageReader.acquireNextImage();
//这个也是关键
        imageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
            @Override
            public void onImageAvailable(ImageReader reader) {
                Image image = reader.acquireNextImage();
                int width = image.getWidth();
                int height = image.getHeight();
                final Image.Plane[] planes = image.getPlanes();
                final ByteBuffer buffer = planes[0].getBuffer();
                int pixelStride = planes[0].getPixelStride();
                int rowStride = planes[0].getRowStride();
                int rowPadding = rowStride - pixelStride * width;
                getBitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888);
//                Bitmap bitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888);
                getBitmap.copyPixelsFromBuffer(buffer);
//                String filePath = Environment.getExternalStorageDirectory().getPath() + "/hello.jpg";
                //bitmap保存为图片
//                saveBitmap(bitmap, filePath);
                image.close();
            }
        }, null);


    }


    public void saveBitmap(Bitmap bitmap, String filePath) {
        try {
            FileOutputStream outputStream = new FileOutputStream(filePath);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mediaProjection = null;
    }

    public static void saveBitmap(Bitmap bitmap) {
        // 指纹图片存放路径
//        String sdCardDir = Environment.getExternalStorageDirectory() + "/脚本/";
        String sdCardDir = Environment.getExternalStorageDirectory() + "/脚本/截图测试";

        try {
            File dirFile = new File(sdCardDir);
            if (!dirFile.exists()) {              //如果不存在，那就建立这个文件夹
                dirFile.mkdirs();
            }
            File file = new File(sdCardDir, String.valueOf(System.currentTimeMillis()) + ".png");
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

}
